/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vista.abms;

import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelo.*;
import util.HibernateUtil;
import util.Tupla;
import vista.interfaces.ICallBackGen;

/**
 *
 * @author Administrador
 */
public class PantallaGestionarRecurso extends javax.swing.JInternalFrame {

    private Class claseBase;
    private int id = -1;
    private Recurso recurso;
    private ICallBackGen callback;
    
    /**
     * Creates new form PantallaGestionarRecurso
     */
    public PantallaGestionarRecurso(Class claseBase) {
        this.claseBase = claseBase;
        initComponents();
        initCombos();
        initPorClase();
    }
    
    public PantallaGestionarRecurso(Class claseBase, int id) {
        this.claseBase = claseBase;
        this.id = id;
        initComponents();
        initCombos();
        initLoadComponent();
        initPorClase(); 
    }    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        cmbUnidadMedida = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        cmbEstado = new javax.swing.JComboBox();
        jPanel1 = new javax.swing.JPanel();
        cmbStockeable = new javax.swing.JCheckBox();
        jLabel4 = new javax.swing.JLabel();
        cmbComprable = new javax.swing.JCheckBox();
        jLabel5 = new javax.swing.JLabel();
        btnCancelar = new javax.swing.JButton();
        btnCrearModificar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setTitle("Gestionar Recursos");

        jLabel1.setText("Nombre del Recurso a Agregar:");

        jLabel2.setText("Unidad de Medida:");

        jLabel3.setText("Estado:");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Opciones Generales"));

        cmbStockeable.setSelected(true);
        cmbStockeable.setText("Éste recurso puede tener Stock");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jLabel4.setText("( Todos los recursos de este tipo tienen Stock en la empresa )");

        cmbComprable.setSelected(true);
        cmbComprable.setText("Éste recurso puede generar Ordenes de Compra");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jLabel5.setText("(Todos los recursos de este tipo pueden agregarse en una orden de compra)");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cmbStockeable, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cmbComprable, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 351, Short.MAX_VALUE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(cmbStockeable)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cmbComprable)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5))
        );

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/block.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnCrearModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/add.png"))); // NOI18N
        btnCrearModificar.setText("Crear");
        btnCrearModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCrearModificarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtNombre)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
                            .addComponent(cmbUnidadMedida, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(cmbEstado, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnCrearModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbUnidadMedida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmbEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnCrearModificar))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnCrearModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCrearModificarActionPerformed
        if(txtNombre.getText().isEmpty())
        {
            mostrarMensaje(JOptionPane.INFORMATION_MESSAGE,"Atencion!","Ingrese un nombre para el Recurso");
            return;
        }   
        
        if(this.id==-1)
        {
            // Creo uno nuevo
            if(this.claseBase == Material.class)
            {
                this.recurso = new Material();
            }
            else if(this.claseBase == Herramienta.class)
            {
                this.recurso = new Herramienta();
            }
        }

        // Si tengo el objeto, lo actualizo
        if(this.recurso!=null)
        {
            // EStado
            Tupla tpe = (Tupla) cmbEstado.getSelectedItem();
            this.recurso.setEstado(tpe.getNombre());
            
            this.recurso.setNombre(txtNombre.getText());
            
            this.recurso.setEsComprable(cmbComprable.isSelected());
            this.recurso.setEsStockeable(cmbStockeable.isSelected());
            
            Tupla tpudm = (Tupla) cmbUnidadMedida.getSelectedItem();
            
            try
            {
                HibernateUtil.beginTransaction();
                UnidadDeMedida udm = (UnidadDeMedida) HibernateUtil.getSession().load(UnidadDeMedida.class,tpudm.getId());
                HibernateUtil.commitTransaction();
                this.recurso.setUnidadDeMedida(udm);
            }catch(Exception e)
            {
                mostrarMensaje(JOptionPane.ERROR_MESSAGE,"Error!","No se pudo cargar la Unidad De Medida");
                return;
            }
        }
        
        // GUARDO EN LA DB
        try
        {
            HibernateUtil.beginTransaction();
            HibernateUtil.getSession().saveOrUpdate(this.recurso);
            HibernateUtil.commitTransaction();

        }catch(Exception ex)
        {
            HibernateUtil.rollbackTransaction();
            mostrarMensaje(JOptionPane.ERROR_MESSAGE,"Error!","Se produjo un error al Crear el nuevo Recurso");
            return;
        }              
        
        if(this.id==-1)
        {
            mostrarMensaje(JOptionPane.INFORMATION_MESSAGE,"Exito!","El Nuevo Recurso se agrego exitosamente !");
        }
        else
        {
            mostrarMensaje(JOptionPane.INFORMATION_MESSAGE,"Exito!","El Nuevo Recurso se modifico exitosamente !");
        }
        if(this.callback!=null)
        {
            this.callback.actualizar(this.recurso.getId(),PantallaGestionarRecursos.CALLBACK_NUEVO_RECURSO,this.recurso.getClass());
        }
        
        this.dispose();
        
        // Llamar al CallBack si hay
        
    }//GEN-LAST:event_btnCrearModificarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnCrearModificar;
    private javax.swing.JCheckBox cmbComprable;
    private javax.swing.JComboBox cmbEstado;
    private javax.swing.JCheckBox cmbStockeable;
    private javax.swing.JComboBox cmbUnidadMedida;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables

    private void initCombos() {
        initComboUnidadMedida();
        initComboEstado();
    }

    private void initComboUnidadMedida() {
        
        if(this.claseBase == Material.class)
        {
            try
            {
                HibernateUtil.beginTransaction();
                List<UnidadDeMedida> listaUnidades = HibernateUtil.getSession().createQuery("FROM UnidadDeMedida").list();
                HibernateUtil.commitTransaction();

                for (int i = 0; i < listaUnidades.size(); i++) {
                    UnidadDeMedida udm = listaUnidades.get(i);
                    Tupla tp = new Tupla(udm.getId(),udm.getNombre()+" ["+udm.getAbreviatura()+"]");
                    cmbUnidadMedida.addItem(tp);
                }
            }catch(Exception e)
            {
                mostrarMensaje(JOptionPane.ERROR_MESSAGE,"Error!","No se pudo cargar el listado de Unidades de Medida");
                this.dispose();
            }
        }
        else if(this.claseBase == Herramienta.class)
        {
            cmbUnidadMedida.addItem(new Tupla(UnidadDeMedida.ID_UNIDAD_BASE,"Unidad [UN]"));
            cmbUnidadMedida.setEnabled(false);
        }
    }

    private void initComboEstado() {
        
        cmbEstado.addItem(new Tupla(0,Recurso.ESTADO_ALTA));
        cmbEstado.addItem(new Tupla(1,Recurso.ESTADO_BAJA));
        
    }
    
    /**
     * Muestra un mensaje
     * @param tipo
     * @param titulo
     * @param mensaje 
     */
    public void mostrarMensaje(int tipo,String titulo,String mensaje)
    {
         JOptionPane.showMessageDialog(this.getParent(),mensaje,titulo,tipo);
    }

    private void initLoadComponent() {
        // Cargo el Recurso
        try{
            HibernateUtil.beginTransaction();
            this.recurso = (Recurso) HibernateUtil.getSession().load(Recurso.class,this.id);
            HibernateUtil.commitTransaction();
        }catch(Exception e){
            mostrarMensaje(JOptionPane.ERROR_MESSAGE,"Error!","No se pudo cargar el Recurso Indicado");
            this.dispose();
        }
        
        if(this.recurso!=null)
        {
            // Cargo los datos del recurso que me pasaron para modificarlo
            btnCrearModificar.setText("Modificar");
            btnCrearModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/Modify.png")));
            
            txtNombre.setText(this.recurso.getNombre());
            
            // Estado
            for (int i = 0; i < cmbEstado.getItemCount(); i++) {
                Tupla tp = (Tupla) cmbEstado.getItemAt(i);
                if(tp.getNombre().equals(this.recurso.getEstado()))
                {
                    cmbEstado.setSelectedIndex(i);
                }
            }
            
            // Unidad De Medida
            for (int i = 0; i < cmbUnidadMedida.getItemCount(); i++) {
                Tupla tp = (Tupla) cmbUnidadMedida.getItemAt(i);
                if(tp.getId()==this.recurso.getUnidadDeMedida().getId())
                {
                    cmbUnidadMedida.setSelectedIndex(i);
                }
            }
            // Stockeable y Comprable
            cmbComprable.setSelected(this.recurso.isEsComprable());
            cmbStockeable.setSelected(this.recurso.isEsStockeable());
        }
    }

    private void initPorClase() {
        if(this.claseBase == Herramienta.class)
        {
            this.cmbComprable.setSelected(true);
            this.cmbComprable.setEnabled(false);
            this.cmbStockeable.setSelected(true);
            this.cmbStockeable.setEnabled(false);
        }
    }

    public void setCallback(ICallBackGen callback) {
        this.callback = callback;
    }
    
    
    
}
